<!--
 * @Description: 基建出库退库申请
 * @Version: 2.0
 * @Autor: gaofang
 * @Date: 2020-04-11 18:29:13
 * @LastEditors: jerry.zzy
 * @LastEditTime: 2021-08-20 09:13:50
-->
<template>
  <a-card>
    <p style="font-size: 18px; text-align: center">基建出库退库申请</p>
    <br />
    <!-- 顶部的信息  -->
    <a-form-model ref="ruleForm" :model="Form" v-bind="layout" :rules="rules">
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号" prop="document" ref="document">
            <a-input
              style="border: 0"
              v-model="Form.document"
              disabled
            ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="仓库名称">
            <a-input v-model="Form.applicationDepot_dictText" disabled>
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="申请部门">
            <a-input v-model="Form.deptId_dictText" disabled> </a-input>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库存组织">
            <a-input v-model="Form.pkCalbody_dictText" disabled> </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="公司" ref="pkCorpName" prop="pkCorpName">
            <a-input v-model="Form.pkCorp_dictText" disabled> </a-input>
          </a-form-model-item>
        </a-col>
        <!-- <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务流程">
            <a-input v-model="Form.cbiztype_dictText" disabled> </a-input>
          </a-form-model-item>
        </a-col> -->
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="在建项目"
            ref="cprojectid_dictText"
            prop="cprojectid_dictText"
          >
            <a-input v-model="Form.cprojectid_dictText" disabled />
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="备注" ref="" prop="">
            <a-input v-model="Form.remark" disabled />
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="单据日期"
            prop="document_date"
            ref="document_date"
          >
            <a-date-picker
              v-model="Form.document_date"
              type="date"
              placeholder="请选择时间"
              style="width: 100%"
              @change="
                (a, b) => {
                  this.Form.a = a;
                  this.Form.document_date = b;
                  this.Form.balance = b;
                }
              "
            />
          </a-form-model-item>
        </a-col>
      </a-row>

      <!-- 根据源单生成  -->

      <!-- 生成原单按钮组件 -->
      <infrasConsOutCancelApplyOrigin
        v-if="!updateTag"
        @select-data="setGoodsListInfoByOrigin"
      ></infrasConsOutCancelApplyOrigin>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        style="margin-top: 10px"
        :scroll="{ x: 2000 }"
        :pagination="false"
      >
        <!-- 数量 -->
        <span slot="quantity" slot-scope="text, record">
          <a-input-number v-model="record.quantity" :step="0.001" />
        </span>

        <!-- 备注 -->
        <span slot="remark" slot-scope="text, record">
          <a-input v-model="record.remark" />
        </span>

        <template slot="action" slot-scope="text, record">
          <span v-if="record.isNew">
            <a @click="cancle(record.key)">取消</a>
          </span>
        </template>
      </a-table>

      <a-row style="margin-top: 20px">
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="审核人" ref="inspector" prop="inspector">
            <a-select
              v-model="Form.inspector"
              showSearch
              @change="getInspectorId"
              style="width: 100%"
            >
              <a-select-option
                v-for="item in inspectorList"
                :key="item.userId"
                :value="item.userId + '|' + item.workNo + '|' + item.userName"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="审核日期">
            <a-date-picker
              v-model="Form.balance"
              type="date"
              style="width: 100%"
              disabled
            />
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="制单人">
            <a-input disabled v-model="Form.singleProducerName"> </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row>
        <center>
          <a-button @click="submit" style="margin-right: 20px"> 保存 </a-button>

          <a-button style="margin-right: 20px" disabled> 审核 </a-button>
        </center>
      </a-row>
    </a-form-model>
  </a-card>
</template>
<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
import moment from "moment";

import infrasConsOutCancelApplyOrigin from "./infrasConsOutCancelApplyOrigin.vue"; //

// 规则
const rules = {
  document: [
    {
      required: true,
      message: "单据号不能为空！",
      trigger: "change",
    },
  ],

  client: [
    {
      required: true,
      message: "客户不能为空",
      trigger: "change",
    },
  ],
  sendReceiveType: [
    {
      required: true,
      message: "收发类别不能为空！",
      trigger: "change",
    },
  ],

  inspector: [
    {
      required: true,
      message: "审核人不能为空！",
      trigger: "change",
    },
  ],
  // 仓位
  position: [
    {
      required: true,
      message: "仓位不能为空！",
      trigger: "change",
    },
  ],

  // 库管员
  cwhsmanager: [
    {
      required: true,
      message: "库管员不能为空！",
      trigger: "change",
    },
  ],

  // 业务流程
  // cbiztype: [
  //   {
  //     required: true,
  //     message: "业务类型不能为空！",
  //     trigger: "change",
  //   },
  // ],
  // 库存组织
  pk_calbody: [
    {
      required: true,
      message: "库存组织不能为空！",
      trigger: "change",
    },
  ],
  // 公司
  pk_corp: [
    {
      required: true,
      message: "公司不能为空！",
      trigger: "change",
    },
  ],
  document_date: [
    {
      required: true,
      message: "单据日期不能为空！",
      trigger: "change",
    },
  ],
};

// 列表
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },
  // {
  //   title: "仓位",
  //   dataIndex: "position",
  //   key: "position",
  //   align: "center",
  // },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
    // scopedSlots: { customRender: "inventoryName" },
  },
  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    dataIndex: "measname",
    key: "measname",
    align: "center",
  },
  {
    title: "辅助单位",
    key: "auxiliaryUnit",
    dataIndex: "auxiliaryUnit",
    align: "center",
    width: 150,
    // scopedSlots: { customRender: "auxiliaryUnit" },
  },
  {
    title: "数量",
    key: "quantity",
    dataIndex: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },
  {
    title: "单价",
    key: "unitPrice",
    dataIndex: "unitPrice",
    align: "center",
    // scopedSlots: { customRender: "unitPrice" },
  },
  {
    title: "金额",
    key: "money",
    dataIndex: "money",
    align: "center",
    // scopedSlots: { customRender: "money" },
  },
  {
    title: "源单单号",
    key: "sourceNumber",
    dataIndex: "sourceNumber",
    align: "center",
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
  // {
  //   title: "操作",
  //   dataIndex: "action",
  //   key: "action",
  //   align: "center",
  //   fixed: "right",
  //   scopedSlots: { customRender: "action" },
  // },
];

export default {
  components: {
    infrasConsOutCancelApplyOrigin,
  },
  data() {
    return {
      Form: {},

      storageList: [], // 仓库列表
      depTree: [], // 部门列表
      clientList: [], // 客户
      SyncBusinessTypeVoList: [], // 业务流程列表
      warehouseOrganizationList: [], // 库存组织列表
      inspectorList: [], // 审核人
      inventoryList: [], // 存货列表
      Auxiliary_Unitlist: [], // 辅助单位

      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      rules,
      columns,
      dataSource: [],

      updateTag: false,
    };
  },

  watch: {
    $route: function (to) {
      if (to.path == "/infrasConsOutCancelApply") {
        this.initInfoMount();
      }
    },
  },
  mounted() {
    this.initInfoMount();
    this.judgeDocument(); //判断单据号是否为空
    this.getInspectorList(); // 仓库审核人员
  },
  methods: {
    // ————判断单据号是否为空————
    judgeDocument() {
      setTimeout(() => {
        if (this.Form.document === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },
    /* ------------------------------- 其他,表头和表尾 ----------------------------- */
    // 申请单号
    getApplyOrder() {
      let queryPath = "?string=JJCKTS-";
      comHttp.getOrder(queryPath).then((res) => {
        this.Form.document = res.message;
      });
    },
    // 审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.inspectorList.push(data);
        }
      });
    },
    // 获取审核人Id
    getInspectorId(value, options) {
      this.Form.inspectorId = options.key;
    },

    /* -------------------------- 表格 ------------------------- */

    // 通过源单生成数据
    setGoodsListInfoByOrigin(data) {
      console.log("传递过来的数据:::::", data);
      this.Form.deliveryContentId = data.deliveryContentId; //基建出库表单物品ID
      // 给表单赋值
      // this.Form.applicationDepot_dictText = data.applicationDepot_dictText; // 仓库名称
      // 部门
      this.Form.deptId = data.deptId;
      this.Form.deptId_dictText = data.deptId_dictText;
      // 所属仓库
      this.Form.applicationDepot_dictText = data.applicationDepot_dictText;
      this.Form.applicationDepot = data.applicationDepot;

      // 业务类型
      // this.Form.cbiztype = data.cbiztype;
      // this.Form.cbiztype_dictText = data.cbiztype_dictText;

      // 库管员
      this.Form.cwhsmanagerid_dictText = data.cwhsmanagerid_dictText;
      this.Form.cwhsmanagerid = data.cwhsmanagerid;

      // 库存组织
      this.Form.pkCalbody = data.pkCalbody;
      this.Form.pkCalbody_dictText = data.pkCalbody_dictText;

      // 收发类别
      this.Form.sendReceiveType_dictText = data.sendReceiveType_dictText;
      this.Form.sendReceiveType = data.sendReceiveType;

      // 公司
      this.Form.pkCorp_dictText = data.pkCorp_dictText;
      this.Form.pkCorp = data.pkCorp;

      // 在建项目
      this.Form.cprojectid_dictText = data.cprojectid_dictText;
      this.Form.cprojectid = data.cprojectid;

      // 备注
      this.Form.remark = data.remark;

      this.Form.applicationDepot_dictText = data.goodsList[0].depotId_dictText; // 仓库名称

      this.dataSource = data.goodsList; // 给列表赋值

      this.dataSource.forEach((element) => {
        element.remark = "";
        // element.sourceNumber=data.document;
      });
    },

    // 页面和路由跳转加载函数
    initInfoMount() {
      if (typeof this.$route.query.Id != "undefined") {
        console.log("--------- 更新视图 销售退库  ----------");
        this.routerJumpSetInitInfo(this.$route.query.Id);
      } else {
        this.initInfo();
      }
    },
    // 初始化加载信息
    initInfo() {
      this.updateTag = false;
      this.Form = {
        document: "", // 单据号
        document_date: moment().format("YYYY-MM-DD"),
        balance: moment().format("YYYY-MM-DD"),
        singleProducerName: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
      };
      this.dataSource = [];
      this.getApplyOrder();
    },

    // 路由跳转,设置初始化信息
    routerJumpSetInitInfo(id) {
      this.updateTag = true;
      comHttp.getOutStorageApplyInfoById("?id=" + id).then((res) => {
        console.log(res);
        this.Form = {};
        this.dataSource = [];
        /* ------------- 设置表单信息 -------------- */
        this.Form.id = res.result.list[0].id;
        this.Form.document = res.result.list[0].document;
        this.$set(this.Form, "document_date", res.result.list[0].documentDate);
        this.Form.applicationDepot_dictText = res.result.list[0].storname; // 仓库名称
        // 部门
        this.Form.deptId_dictText = res.result.list[0].deptId_dictText;
        // 所属仓库

        // 客户
        this.Form.clientId_dictText = res.result.list[0].clientId_dictText;
        // 业务类型
        this.Form.cbiztype_dictText = res.result.list[0].cbiztype_dictText;

        // 库管员
        this.Form.cwhsmanagerid_dictText =
          res.result.list[0].cwhsmanagerid_dictText;

        // 库存组织
        this.Form.pkCalbody_dictText = res.result.list[0].pkCalbody_dictText;

        // 收发类别
        this.Form.sendReceiveType_dictText =
          res.result.list[0].sendReceiveType_dictText;

        // 公司
        this.Form.pkCorp_dictText = res.result.list[0].pkCorp_dictText;
        this.Form.pkCorp = res.result.list[0].pkCorp;

        // 在建项目
        this.Form.cprojectid_dictText = res.result.list[0].cprojectid_dictText;
        this.Form.cprojectid = res.result.list[0].cprojectid;

        // 备注
        this.Form.remark = res.result.list[0].remark;

        // 审核人
        this.$set(this.Form, "inspectorId", res.result.list[0].inspector);
        this.$set(
          this.Form,
          "inspector",
          res.result.list[0].inspector_dictText
        );

        // 制单人
        this.Form.singleProducerName =
          res.result.list[0].singleProducer_dictText;

        let i = 0;
        res.result.list.forEach((element) => {
          let data = {
            id: element.twoId,
            key: i + 1,
            invname: element.invname,
            invcode: element.invcode,
            invspec: element.invspec,
            measname: element.measname,
            auxiliaryUnit: element.auxiliaryUnit_dictText,
            sourceNumber: element.sourceNumber,
            remark: element.remarks,
            quantity: element.quantity,
          };
          i = i + 1;
          this.dataSource.push(data);
        });
      });
    },

    // 新增提交
    addSubmit() {
      let array = [];
      console.log("array", this.dataSource);

      this.dataSource.forEach((element) => {
        let data = {
          deliveryContentId: element.deliveryContentId, //基建出库表单物品ID
          objectInformationId: element.objectInformationId, //据源单生成的物品列表接口中
          inventoryId: element.inventoryId, //存货id
          // auxiliaryUnit: element.auxiliaryUnit,
          quantity: element.quantity, //数量
          sourceNumber: element.sourceNumber, //源单单号
          remark: element.remark, //备注
          depotId: element.depotId, // 仓库名称
        };
        array.push(data);
      });

      //  let  array
      let submitData = {
        balance: moment(this.Form.document_date).format("YYYY-MM-DD"),
        auditMark: 2, // 未审核是 1 , 已审核是 2
        // bookkeepingMark: 2,
        inOutCategoryIdentification: 10, // 基建退库
        inOutIdentification: 3, // 退库

        document: this.Form.document, // 单据号
        // cbiztype: this.Form.cbiztype, // 业务类型
        deptId: this.Form.deptId, // 部门
        pkCorp: this.Form.pkCorp, // 公司
        cprojectid: this.Form.cprojectid, // 在建项目
        remark: this.Form.remark, // 备注
        // clientId: this.Form.clientId, // 客户
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"), // 单据日期
        pkCalbody: this.Form.pkCalbody, // 库存组织

        inspector: this.Form.inspectorId, // 审核人
        singleProducer: this.Form.singleProducerId, // 制单人
        warehouseReturnRequestFormEntityList: array,
      };

      console.log("要提交的数据为:::::", submitData);
      // 保存退库信息
      comHttp.saveStockReturnInfo(submitData).then((res) => {
        if (res.code == 200) {
          this.$message.success("保存成功");
          this.initInfo();
        } else {
          this.$message.error("保存失败");
        }
      });
    },
    // 修改提交
    updateSubmit() {
      let array = [];
      this.dataSource.forEach((element) => {
        let data = {
          id: element.id,
          quantity: element.quantity,
          remark: element.remark,
        };
        array.push(data);
      });

      let submitForm = {
        // documentDate: this.Form.documentDate,
        id: this.Form.id,
        inspector: this.Form.inspectorId,
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"),
        warehouseReturnRequestFormEntityList: array,
      };

      // 修改全部的信息
      comHttp.warehousereturnrequest(submitForm).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success("修改成功");
        } else {
          this.$message.error("修改失败");
        }
      });
    },
    // 提交
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //  这是新增提交
          if (this.updateTag == false) {
            this.addSubmit();
          } else {
            // 这是修改提交
            this.updateSubmit();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
